package com.lu.aio;

import com.lu.aio.server.AioServer;
import lombok.SneakyThrows;

import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @program lu-netty
 * @description:
 * @author: zhanglu
 * @create: 2022-06-10 17:24:00
 */
public abstract class ChannelInitializer implements CompletionHandler<AsynchronousSocketChannel, AioServer> {

    /**
     * 连接成功 - 初始化事件(读、写)处理器
     * @param channel
     * @param attachment
     */
    @Override
    public void completed(AsynchronousSocketChannel channel, AioServer attachment) {
        try {
            attachment.serverSocketChannel().accept(attachment, this);
            initChannel(channel);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    @Override
    public void failed(Throwable exc, AioServer attachment) {
        exc.printStackTrace();
    }

    protected abstract void initChannel(AsynchronousSocketChannel channel) throws Exception;

}
